import { useState, useEffect } from "react";
import { Form, message } from "antd";
import { CommonModal } from "@/views/components/CommonModal";
import { productOutboundOrderAssignedReturnClerk, queryTakeUserList } from "../service";
import { Select } from "@/views/components/PrefixPlaceholder";

const AssignedReturnClerkModal = ({ visible, checkedRows, handleCancel, fetchList, filteredArray }) => {
	const [form] = Form.useForm();
	const [codesArrayNum, setCodesArrayNum] = useState(false);
	const [userData, setUserData] = useState([]);
	const [pickerName, setPickerName] = useState("");
	const [pickerAccount, setPickerAccount] = useState("");

	const handleUserList = async () => {
		const { data, success } = await queryTakeUserList({
			current: 1,
			size: 2000,
			businessType: 4,
			forbidMenulds: "",
			username: ""
		});
		if (success) {
			if (data) {
				const list = data.map(x => {
					x.label = x.name + "(" + x.account + ")";
					x.value = x.id;
					return x;
				});
				setUserData(list);
			}
		}
	};
	useEffect(() => {
		handleUserList();
		const codesArray = filteredArray.map(item => item.productOutboundNo);
		setCodesArrayNum(codesArray.join(","));
		if (visible) {
			form.resetFields();
		}
	}, [visible]);

	const onOk = () => {
		form.validateFields().then(async value => {
			const { success } = await productOutboundOrderAssignedReturnClerk({
				pickerId: value.pickerId,
				productOutboundNo: codesArrayNum,
				pickerName: pickerName,
				pickerAccount: pickerAccount
			});
			if (success) {
				message.success("操作成功");
				onCancel();
				fetchList();
			}
		});
	};
	const onCancel = () => {
		handleCancel();
		form.resetFields();
	};
	const onChange = e => {
		const filteredArray = userData.filter(item => item.id == e);
		setPickerName(filteredArray[0].name);
		setPickerAccount(filteredArray[0].account);
	};
	return (
		<CommonModal title={{ title: "指派退货员" }} visible={true} onOk={onOk} onCancel={onCancel} width="494px" minHeight="150px">
			<Form form={form} name="mark-unuaual-modal">
				<Form.Item label="" name="pickerId" rules={[{ required: true, message: "请选择退货员" }]}>
					<Select showSearch onChange={onChange} placeholder="请选择退货员" allowClear options={userData}></Select>
				</Form.Item>
			</Form>
		</CommonModal>
	);
};

export default AssignedReturnClerkModal;
